package com.wangyk.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.wangyk.gateway.constant.CookieConstant;
import com.wangyk.gateway.constant.RedisConstant;
import com.wangyk.gateway.utils.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * 设置权限拦截的过滤器（区分买家和卖家）
 */
@Component
public class AuthFilter extends ZuulFilter
{
    /**
     * 需要操作数据库
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 设置过滤器的类型
     */
    public String filterType()
    {
        return PRE_TYPE;
    }

    /**
     * 设置过滤器的顺序，数字越小优先级越高
     */
    public int filterOrder()
    {
        return PRE_DECORATION_FILTER_ORDER - 1;
    }

    public boolean shouldFilter()
    {
        return true;
    }

    /**
     * 填写业务逻辑
     */
    public Object run()
        throws ZuulException
    {
        /**
         * 获取当前请求的上下文
         * */
        RequestContext currentContext = RequestContext.getCurrentContext();
        /**
         * 从上下文中获取请求
         * */
        HttpServletRequest request = currentContext.getRequest();
        /**
         * 可以从url中获取，或者是cookies或者是header中获取参数
         * */
        String uri = request.getRequestURI();
        System.out.println("uri:" + uri);
        /**
         * 如果没有权限
         * */
        if (true)
        {
            /**
             * /order/create只能买家访问（cookie中有openid）
             * /order/finish只能卖家访问（cookie中有token，redis中有对应的值）
             * /product/list买家和卖家都可以访问
             * */
            /**
             * 判断买家的权限，
             * 买家有token，从cookie中获取token
             * */
            if ("/user/user/auth/buyer".equals(uri))
            {
                Cookie cookie = CookieUtil.get(request, CookieConstant.OPENID);
                if (cookie == null || StringUtils.isEmpty(cookie.getValue()))
                {
                    //表示为不通过
                    currentContext.setSendZuulResponse(false);
                    //设置Http的返回码
                    currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
                }
            }
            /**
             * 判断卖家的权限，
             * cookie不能为null
             * cookie的token不能为null
             * redis中的token_token的值不能为null
             * */
            if ("/user/user/auth/seller".equals(uri))
            {
                Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
                if (cookie == null || StringUtils.isEmpty(cookie.getValue()) ||
                    StringUtils.isEmpty(stringRedisTemplate.opsForValue()
                        .get(String.format(RedisConstant.TOKEN_TEMPLATE, cookie.getValue()))))
                {
                    //表示为不通过
                    currentContext.setSendZuulResponse(false);
                    //设置Http的返回码
                    currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
                }
            }
        }
        return null;
    }
}
